package com.bootdo.system.service.impl;

import com.bootdo.common.domain.Tree;
import com.bootdo.common.utils.BuildTree;
import com.bootdo.system.dao.ItemDao;
import com.bootdo.system.domain.ItemDO;
import com.bootdo.system.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检查项目service
 *
 * @author zhouxm
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemDao itemDao;

    @Override
    public ItemDO get(Long itemId) throws Exception {
        return itemDao.get(itemId);
    }

    @Override
    public List<ItemDO> list(Map<String, Object> map) {
        return itemDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) throws Exception {
        return itemDao.count(map);
    }

    @Override
    public int save(ItemDO itemDO) throws Exception {
        return itemDao.save(itemDO);
    }

    @Override
    public int update(ItemDO itemDO) throws Exception {
        return itemDao.update(itemDO);
    }

    @Override
    public int remove(Long itemId) throws Exception {
        return itemDao.remove(itemId);
    }

    @Override
    public int batchRemove(Long[] itemIds) throws Exception {
        return itemDao.batchRemove(itemIds);
    }

    @Override
    public Tree<ItemDO> getTree() throws Exception {
        List<Tree<ItemDO>> trees = new ArrayList<>();
        List<ItemDO> itemList = itemDao.list(new HashMap<String, Object>(16));
        for (ItemDO itemDO : itemList) {
            Tree<ItemDO> tree = new Tree<>();
            tree.setId(itemDO.getItemId().toString());
            tree.setParentId(String.valueOf(itemDO.getParentId()));
            tree.setText(itemDO.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        return BuildTree.build(trees);
    }

    @Override
    public boolean checkItemHasUser(Long itemId) throws Exception {
        int result = itemDao.getItemUserNumber(itemId);
        return result == 0;
    }

    @Override
    public List<Long> listChildrenIds(Long parentId) throws Exception {
        List<ItemDO> itemList = list(null);
        return treeMenuList(itemList, parentId);
    }

    private List<Long> treeMenuList(List<ItemDO> menuList, long pid) {
        List<Long> childIds = new ArrayList<>();
        for (ItemDO mu : menuList) {
            //遍历出父id等于参数的id，add进子节点集合
            if (mu.getParentId() == pid) {
                //递归遍历下一级
                treeMenuList(menuList, mu.getItemId());
                childIds.add(mu.getItemId());
            }
        }
        return childIds;
    }
}
